//每一个state都有播放动画的能力

import { AnimationClip, Sprite, SpriteFrame, UITransform, animation ,Animation } from "cc";
import { PlayerStateMachine } from "../Script/Player/PlayerStateMachine";
import ResourceManager from "../Runtime/ResourceManager";
import { TILE_WIDTH, TILE_HEIGHT } from "../Script/Tile/TileManager";
import { StateMachine } from "./StateMachine";

//需要知道anminclip
//
export const ABIMATION_SPEED = 1 / 8  //帧数  8帧
export default class State {
    private animationClip: AnimationClip
    


    //第一个参数状态机？资源路径？默认播放一次还是无数次
    constructor(private fsm: StateMachine, private path: string, private wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal,
        private events: any[] =[]) {
        this.init()
    }


    async init() {



        //加载资源
        const promise = ResourceManager.Instance.loadDir(this.path)

        this.fsm.waitingList.push(promise)
        const spriteFrames = await promise


        //甚至clip
        this.animationClip = new AnimationClip()


        

        //轨道
        const track = new animation.ObjectTrack()//创建对象轨道
        track.path = new animation.TrackPath().toComponent(Sprite).toProperty('spriteFrame'); // 指定轨道路径，即指定目标对象为 "Foo" 子节点的 "position" 属性


        //处理资源数组
        const frams: Array<[number, SpriteFrame]> = spriteFrames.map((item, index) => [ABIMATION_SPEED * index, item]) //得到关键帧列表
        track.channel.curve.assignSorted(
            frams
            //         [ // 为 x 通道的曲线添加关键帧
            //     [0.4, ({ value: 0.4 })],
            //     [0.6, ({ value: 0.6 })],
            //     [0.8, ({ value: 0.8 })],
            // ]
        )

        //最后将轨道添加到动画剪辑
        this.animationClip.addTrack(track)
        this.animationClip.name = this.path

        this.animationClip.wrapMode = this.wrapMode


        //震动
        // for (const event of this.events) {
        //     console.log(event)
        //     // this.animationClip.events.push(event)
        //     this.animationClip.events.push(event)
        // }
        // animation.clips = animation.clips;




        //
        this.animationClip.duration = frams.length * ABIMATION_SPEED //整个动画剪辑的周期
    }
    addComponent(Sprite: any) {
        throw new Error("Method not implemented.");
    }
    getComponent(UITransform: any) {
        throw new Error("Method not implemented.");
    }


    //播放动画--最后一步
    run() {

        if (this.fsm.animationsComponent?.defaultClip?.name === this.animationClip.name) {
            return
        }
        this.fsm.animationsComponent.defaultClip = this.animationClip
        this.fsm.animationsComponent.play()
    }

}